package com.maixin.code.dao;

import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;

import com.maixin.code.entity.Authority;
import com.maixin.code.store.ComboStore;

public class RoleAuthDAO extends BaseDAO<Authority>{
	
	/**
	 * 
	 * @return
	 */
	public List<ComboStore> findParAuth(){
		String hql = "select a.id key ,a.authorityname value from authority a  where a.parentId is null";
		SQLQuery query = (SQLQuery) getSession().createSQLQuery(hql).setResultTransformer(Transformers.aliasToBean(ComboStore.class));;
		query.addScalar("key", Hibernate.STRING);
		query.addScalar("value", Hibernate.STRING);
		return query.list();
	}
	
	
	/**
	 * 获得角色管理的权限列表
	 * @param roleid
	 * @return
	 */
	public List<Authority> findAllRoles(Integer roleid){
		try {
			String hql = " select rt.id id,rt.roleid roleid,a.id authorityid,a.authorityname authorityname, "+
					" a.authoritycode authoritycode, a.remark remark, r.rolename rolename "+
					" from roleauthority rt inner join authority a on rt.authoritycode = a.authoritycode "+
					" left join role r on rt.roleid = r.id ";
			if(null!=roleid){
				hql += "where r.id = :roleid";
			}
			SQLQuery query = (SQLQuery) super.getSession().createSQLQuery(hql).setResultTransformer(Transformers.aliasToBean(Authority.class));
			query.addScalar("id", Hibernate.INTEGER);
			query.addScalar("roleid", Hibernate.INTEGER);
			query.addScalar("authorityid", Hibernate.INTEGER);
			query.addScalar("authorityname", Hibernate.STRING);
			query.addScalar("authoritycode", Hibernate.STRING);
			query.addScalar("remark", Hibernate.STRING);
			query.addScalar("rolename", Hibernate.STRING);
			if(null!=roleid){
				query.setInteger("roleid", roleid);
			}
			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	 * 删除角色对应的权限关系数据
	 * @param roleId
	 */
	public void delRoleAuth(Integer roleId){
		String sql = "delete from roleauthority rt where rt.roleid = :id";
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setInteger("id", roleId);
		query.executeUpdate();
	}

}
